Spring Data JPA查询指定列,并返回实体(改)

您所在的位置:网站首页 jpa specification返回指定列 Spring Data JPA查询指定列,并返回实体(改)

Spring Data JPA查询指定列,并返回实体(改)

2024-07-16 05:25| 来源: 网络整理| 查看: 265

现有PostEntiy实力,包含各种属性,如:

/** * @Auther: DingShuo * @Date: 2018/7/18 11:09 * @Description: */ @Entity public class PostEntity { @Id @GenericGenerator(name = "system-uuid", strategy = "uuid2") @GeneratedValue(generator = "system-uuid") String id; @Column(nullable = false) String title; @Column(nullable = false,columnDefinition="TIMESTAMP") @Temporal(TemporalType.TIMESTAMP) @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") Date createTM; @Lob @Column(columnDefinition="TEXT") String postContent; //余下略 }

想只查询标题title和时间createTM,按照常规用法应该返回的是List,如

** * @Auther: DingShuo * @Date: 2018/7/18 11:57 * @Description: */ @Repository public interface PostEntityRepo extends JpaRepository { @Query(value = "select p.title,p.createTM from PostEntity p") List test(); }

但是这样还是重新遍历再取值,现在想实现如Mybatis里面的查询resultmapper,该怎么办?

先创建一个查询结果的实体,如

/** * @Auther: DingShuo * @Date: 2018/8/14 19:02 * @Description: */ public class TestDTO { String title; Date createTM; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getCreateTM() { return createTM; } public void setCreateTM(Date createTM) { this.createTM = createTM; } public TestDTO(String title, Date createTM) { this.title = title; this.createTM = createTM; } }

在改动JPA的@Repository类中,修改查询方法,如

** * @Auther: DingShuo * @Date: 2018/7/18 11:57 * @Description: */ @Repository public interface PostEntityRepo extends JpaRepository { @Query(value = "select new com.haramasu.daomin2.dto.TestDTO(p.title,p.createTM) from PostEntity p") List test(); }

此后查询结果就是被转为预设的结果实体了。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3